package com.example.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.entity.Newspaper;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.NewspaperMapper;
import com.example.springboot.service.INewspaper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class NewspaperService implements INewspaper {

    @Resource
    NewspaperMapper newspaperMapper;

    //查询所有
    @Override
    public List<Newspaper> list() {
        return newspaperMapper.list();
    }

    //分页
    @Override
    public PageInfo<Newspaper> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<Newspaper> newspapers = newspaperMapper.listByCondition(baseRequest);
        return new PageInfo<>(newspapers);
    }

    //更新
    @Override
    public void update(Newspaper newspaper) {
        Date date = new Date();
        newspaper.setUpdateTime(date);
        try {
        newspaper.setCategory(setCategory(newspaper.getCategories()));
        newspaperMapper.update(newspaper);
        }catch (Exception e){
            throw  new ServiceException("数据更新异常", e);
        }
    }


    //新增
    @Override
    public void save(Newspaper newspaper) {
        Date date = new Date();
        newspaper.setUpdateTime(date);
        try {
            newspaper.setCategory(setCategory(newspaper.getCategories()));
            newspaperMapper.save(newspaper);
        }catch (Exception e){
            throw  new ServiceException("数据插入错误", e);
        }

    }

    private String setCategory(List<String> categories){
        StringBuilder sb = new StringBuilder();
        if (CollUtil.isNotEmpty(categories)){
            categories.forEach(v ->sb.append(v).append(">"));
            return sb.substring(0,sb.lastIndexOf(">"));
        }
        return sb.toString();
    }

    @Override
    public Newspaper getById(Integer id) {
        return newspaperMapper.getById(id);
    }

    //删除
    @Override
    public void deleteById(Integer id) {
        newspaperMapper.deleteById(id);
    }

    @Override
    public Integer deleteByIds(List<Integer> ids) {
        return newspaperMapper.deleteByIds(ids);
    }


}
